#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/29 09:03:39
'''
from flask import Blueprint, jsonify, request
from sqlalchemy import and_
from Common.Utils import Utils, PageParam

from Common.auth import token_auth
from db_logic.client import BllClient
from db_logic.client_cell import BllClientCell
from db_logic.client_cell_user import BllClientCellUser
from db_logic.client_user import BllClientUser
from db_logic.medicament_record import BllMedicamentRecord
from db_logic.medicament_template import BllMedicamentTemplate
from db_logic.meidcament_variety import BllMedicamentVariety
from db_logic.humiture_record import BllHumitureRecord
from db_logic.medicament import BllMedicament

from models.client_models import EntityClient, EntityClientCell, EntityClientCellUser
from models.medicament_models import EntityMedicament, EntityMedicamentRecord, EntityMedicamentTemplate, EntityMedicamentVariety
from models.humiture_models import EntityHumitureRecord

client_router = Blueprint("client", __name__)


# 查看client列表
@client_router.route("/client_list", methods=["POST"])
@token_auth.login_required
def get_client_list():
    func_type = request.values.get("func_type")
    data = BllClient().get_all_client_list(func_type=func_type)
    data_list = Utils.msyql_table_model(data)
    return jsonify(Utils.true_return(data={"data_list": data_list}))


# 查看列表
@client_router.route("/get_list", methods=["GET","POST"])
@token_auth.login_required
def getclient_list():
    seach_word = request.values.get("seach_word")
    func_type = request.values.get("func_type")
    page = request.values.get("page", 1)
    page_size = request.values.get("page_size", 100)
    page_param = PageParam(int(page), int(page_size))
    data = BllClient().get_client_seach(
        seach_word=seach_word, func_type=func_type, page_param=page_param
    )
    data_list = Utils.msyql_table_model(data)
    return jsonify(Utils.true_return(data={"data_list": data_list, "total_count": page_param.totalRecords}))
    

# 新增and编辑
@client_router.route("/add_or_update", methods=["POST"])
@token_auth.login_required
def client_add_update():
    client_id = request.values.get("client_id")
    obj = BllClient().findEntity(
        EntityClient.client_code == request.values.get("client_code")
    )
    finds_list = dir(EntityClient)
    if client_id:
        client_obj = BllClient().findEntity(
            EntityClient.client_id==client_id
        )
        if obj:
            for i in finds_list:
                va = request.values.get(i)
                if va:
                    setattr(client_obj, i, va)
            BllClient().update(client_obj)
            return jsonify(Utils.true_return(msg="修改成功"))
        else:
            return jsonify(Utils.false_return(msg="柜体信息有误"))
    else:
        client_obj = EntityClient()
        for i in finds_list:
            va = request.values.get(i)
            if va:
                setattr(client_obj, i, va)
        BllClient().insert(client_obj)
        return jsonify(Utils.true_return(msg="添加成功"))

    # finds = [
    #     "client_title", "client_name", "client_code", "client_type", "place", "filter_production_date",
    #     "filter_shelf_life_warning_value", "contact_people_name", "contact_phone", "description"
    # ]
    # client_id = request.values.get("client_id")
    # obj = BllClient().findEntity(
    #     EntityClient.client_code == request.values.get("client_code")
    # )
    # if client_id:
    #     client_obj = BllClient().findEntity(
    #         EntityClient.client_id==client_id
    #     )
    #     if obj:
    #         if client_obj.client_id != obj.client_id:
    #             return jsonify(Utils.false_return())
    #     for i in finds:
    #         setattr(client_obj, i, request.values.get(i))
    #     BllClient().update(client_obj)
    #     return jsonify(Utils.true_return(msg="修改成功"))
    # else:
    #     if obj:
    #         return jsonify(Utils.false_return(msg="柜体需要不能重复"))
    #     client_obj = EntityClient()
    #     for i in finds:
    #         setattr(client_obj, i, request.values.get(i))
        
    #     BllClient().insert(client_obj)
    #     return jsonify(Utils.true_return(msg="添加成功"))

# 锁定或解锁柜体
@client_router.route("/update_status", methods=["POST"])
@token_auth.login_required
def update_status():
    status_type = request.values.get("status_type")
    client_id = request.values.get("client_id")
    obj = BllClient()
    client_obj = obj.findEntity(EntityClient.client_id == client_id)
    if client_obj:
        client_obj.is_enabled=status_type
        obj.update(client_obj)
        return jsonify(Utils.true_return(msg="修改成功"))
    else:
        return jsonify(Utils.false_return("柜体不存在"))

# 删除柜体
@client_router.route("/del", methods=["POST"])
@token_auth.login_required
def client_del():
    client_id = request.values.get("client_id")
    drug_obj = BllMedicament().findEntity(EntityMedicament.client_id == client_id)
    if drug_obj:
        return jsonify(Utils.false_return(msg="请先删除柜体内试剂数据"))
    else:
        BllClient().delete(EntityClient.client_id==client_id)
        BllMedicamentRecord().delete(EntityMedicamentRecord.client_id == client_id)
        BllMedicamentTemplate().delete(EntityMedicamentTemplate.client_id == client_id)
        BllHumitureRecord().delete(EntityHumitureRecord.client_id == client_id)

        return jsonify(Utils.true_return(msg="删除成功"))
    # return jsonify(Utils.true_return())


# 清空所有需删除表数据
# rms_user_medicament, rms_medicament_variety, 
# rms_medicament_template,rms_medicament_record,
# rms_medicament_extend,rms_medicament, rms_humiture_record
# 清空指定柜体需删除
# rms_medicament_template,rms_medicament_record,rms_medicament, rms_humiture_record

@client_router.route("/client_empty", methods=["POST"])
@token_auth.login_required
def client_empty():
    client_id = request.values.get("client_id")
    if client_id:
        BllMedicament().delete(EntityMedicament.client_id == client_id)
        BllMedicamentRecord().delete(EntityMedicamentRecord.client_id == client_id)
        BllMedicamentTemplate().delete(EntityMedicamentTemplate.client_id == client_id)
        BllHumitureRecord().delete(EntityHumitureRecord.client_id == client_id)
    else:
        BllClient().empty_table_info()
    return jsonify(Utils.true_return())


# 获取柜子是否有抽屉
@client_router.route("/get_client_drawer", methods=["POST"])
@token_auth.login_required
def get_client_drawer():
    client_id = request.values.get("client_id")
    data_list = BllClientCell().findList(EntityClientCell.client_id==client_id).all()
    if data_list:
        return jsonify(Utils.true_return(data=data_list))
    else:
        return jsonify(Utils.false_return(msg="该柜体没有柜子"))

# 分配抽屉权限展示
@client_router.route("/get_drawer_power", methods=["POST"])
@token_auth.login_required
def get_client_drawer_power():
    drawer_id = request.values.get("drawer_id")
    client_id = request.values.get("client_id")
    page = request.values.get("page", 1)
    page_size = request.values.get("page_size", 10)
    page_param = PageParam(int(page), int(page_size))
    data_list = BllClientCell().get_drawer_power_user_list(
        drawer_id=drawer_id, client_id=client_id, page_param=page_param)
    return jsonify(Utils.true_return(data={"data_list": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))

# 分配抽屉权限
@client_router.route("/set_drawer_power", methods=["POST"])
@token_auth.login_required
def set_client_drawer_power():
    drawer_id = request.values.get("drawer_id")
    client_id = request.values.get("client_id")
    client_code = request.values.get("client_code")
    client_cell_code = request.values.get("client_cell_code")
    set_drawer_info = request.values.get("drawer_user_info")

    set_drawer_info = eval(set_drawer_info)
    cell_user_obj = BllClientCellUser()
    # 获取已有权限的用户信息
    user_id_list = list(set_drawer_info.keys())
    obj_list = cell_user_obj.findList(
        and_(
        EntityClientCellUser.client_id==client_id,
        EntityClientCellUser.client_cell_id==drawer_id,
        EntityClientCellUser.user_id.in_(user_id_list)
        )
    ).all()
    #筛选出被删除的用户
    # drawer_del_user_list = []
    # obj_list = Utils.msyql_table_model(obj_list)
    for i in obj_list:
        user_drawer = set_drawer_info.get(i.user_id)
        if str(user_drawer) == "0":
            cell_user_obj.delete(
                and_(
                    EntityClientCellUser.client_id==i.client_id,
                    EntityClientCellUser.client_cell_id==drawer_id,
                    EntityClientCellUser.user_id==i.user_id
                )
            )
        # set_drawer_info.pop(i.user_id)
        del set_drawer_info[i.user_id]
    # cell_user_obj.session.commit()
    # 筛选出需要添加的用户
    drawer_add_user_list = []
    for k,v in set_drawer_info.items():
        if str(v) == "1":
            drawer_add_user_list.append(k)
    # # 按条件删除
    # for i in drawer_del_user_list:
    #     cell_user_obj.session.delete(i)
    # cell_user_obj.session.commit()
    # 按条件添加
    inster_add_list = []
    for i in drawer_add_user_list:
        obj = EntityClientCellUser(
            client_cell_id=drawer_id,
            client_cell_code=client_cell_code,
            client_code=client_code,
            client_id=client_id,
            user_id=i
        )
        inster_add_list.append(obj)
    cell_user_obj.insert_many(inster_add_list)

    return jsonify(Utils.true_return())


#################################
##验证通过后需要添加至试剂领用处。##
#################################
# 分配禁用用户
@client_router.route("/user_ban_list", methods=["POST"])
@token_auth.login_required
def client_ban_user_list():
    seach_user = request.values.get("seach_user")
    client_id = request.values.get("client_id")
    page = int(request.values.get("page", 1))
    page_size = int(request.values.get("page_size", 10))
    page_param = PageParam(page, page_size)
    data_list = BllClientUser().get_band_user_list(
        seach_user=seach_user, page_param=page_param,
        client_id=client_id
    )
    return jsonify(Utils.true_return(data={"data": Utils.msyql_table_model(data_list), "total_count": page_param.totalRecords}))


# 确认禁用
@client_router.route("/user_ban_confirm", methods=["POST"])
@token_auth.login_required
def client_ban_user_confirm():
    # user_id = request.values.get("user_id")
    # client_id = request.values.get("client_id")
    # data = BllClientUser().inster_user_client(user_id, client_id)
    # if data:
    #     return jsonify(Utils.true_return())
    # else:
    #     return jsonify(Utils.false_return())

    user_id = request.values.get("user_id")
    client_id = request.values.get("client_id")
    data = BllClientUser().del_user_ban_client(
        user_id=user_id, client_id=client_id)
    if data:
        return jsonify(Utils.true_return(msg=""))
    else:
        return jsonify(Utils.false_return(msg=""))

# 取消禁用试剂
@client_router.route("/user_ban_relieve", methods=["POST"])
@token_auth.login_required
def client_user_ban_relieve():
    # user_id = request.values.get("user_id")
    # client_id = request.values.get("client_id")
    # data = BllClientUser().del_user_ban_client(
    #     user_id=user_id, client_id=client_id)
    # if data:
    #     return jsonify(Utils.true_return(msg="删除成功"))
    # else:
    #     return jsonify(Utils.false_return(msg="删除失败"))
    user_id = request.values.get("user_id")
    client_id = request.values.get("client_id")
    data = BllClientUser().inster_user_client(user_id, client_id)
    if data:
        return jsonify(Utils.true_return())
    else:
        return jsonify(Utils.false_return())